import axios from 'axios'
import { ElMessage } from 'element-plus'
import { store } from '@renderer/store'
import router from '@renderer/router'

const serves = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 50000
})

// 设置请求发送之前的拦截器
serves.interceptors.request.use(config => {
  // 设置发送之前数据需要做什么处理
  const userId = store.getters['common/userId']
  console.log(userId, 'userIduserId')
  if (!!userId) {
    config.headers['user-id'] = userId
  }

  return config
}, err => Promise.reject(err))

// 设置请求接受拦截器
serves.interceptors.response.use(response => {
  const code = response.data.code || response.data.status || 0
  // 处理登录失败的问题
  if (code == 4001) {
    store.commit('common/USERID', '')
    router.push({ path: '/login' })
    return Promise.reject()
  }
  // 处理常见的错误
  if (code == 500) {
    if (response.data.msg.indexOf('UserId') == -1) {
      ElMessage.error(response.data.msg)
    }
    return Promise.reject()
  }
  // 处理成功的情况
  if (code === 200 || code === 0) {
    return Promise.resolve((response.data.Data || response.data.result || response.data.data) ?? response.data)
  }
  return Promise.reject(response.data)
}, err => {
  // 判断请求异常信息中是否含有超时timeout字符串
  if (err.message.includes('timeout')) {
    console.log('错误回调', err)
    ElMessage.error('网络超时')
  }
  if (err.message.includes('Network Error')) {
    console.log('错误回调', err)
    ElMessage.error('服务端未启动，或网络连接错误')
  }
  return Promise.reject(err)
})

// 将serves抛出去
export default serves
